package cn.zero.service.impl;

import static cn.zero.wechat.util.WechatUtil.WECHAT_TOKEN_SERVER_URL;

import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.Arrays;
import java.util.Date;
import java.util.Formatter;

import org.apache.commons.lang3.StringUtils;
import org.dom4j.Document;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.alibaba.fastjson.JSONObject;

import cn.zero.model.User;
import cn.zero.model.WechatInfo;
import cn.zero.model.WechatInfo_ID;
import cn.zero.service.UserService;
import cn.zero.service.WechatInfoService;
import cn.zero.service.WechatService;
import cn.zero.type.ParamType;
import cn.zero.util.RegexUtil;
import cn.zero.util.WebUtil;
import cn.zero.wechat.AccessTokenModel;
import cn.zero.wechat.config.WechatCommonConfig;
import cn.zero.wechat.req.WechatMpMessage;
import cn.zero.wechat.resp.TextMessage;
import cn.zero.wechat.util.MessageUtil;
import cn.zero.wechat.util.WechatUtil;

@Service("wechatService")
public class WechatServiceImpl implements WechatService {

	@Autowired
	private UserService userService;

	@Autowired
	private WechatInfoService wechatInfoService;

	@Override
	public String getAppId() {
		return WechatCommonConfig.wechatConfig().getWeixin().getAppId();
	}

	@Override
	public String getSignature(String appid, String nonce_str, String timestamp, String url) {
		return getJSSignature(WechatUtil.getJSTicket(appid), nonce_str, timestamp, url);
	}

	@Override
	public String getWechatAuthorizeUrl(String state, String url, boolean authorize) throws Exception {
		return String.format(
				"https://open.weixin.qq.com/connect/oauth2/authorize?appid=%s&redirect_uri=%s&response_type=code&scope=%s&state=%s#wechat_redirect",
				WechatCommonConfig.wechatConfig().getWeixin().getAppId(), URLEncoder.encode(url, "UTF-8"),
				authorize ? WechatCommonConfig.WECHAT_OAUTH2_SCOPE_USERINFO
						: WechatCommonConfig.WECHAT_OAUTH2_SCOPE_BASE,
				state);
	}

	@Override
	public AccessTokenModel getAuthorizeAccessToken(String code) {
		String retData = null;
		try {
			retData = WebUtil
					.getUrlData(WECHAT_TOKEN_SERVER_URL + String.format("/api/wechat/getauthtoken?appId=%s&code=%s",
							WechatCommonConfig.wechatConfig().getWeixin().getAppId(), code));
		} catch (Exception e) {
			return null;
		}
		return JSONObject.parseObject(retData, AccessTokenModel.class);
	}

	@Override
	public String getAccessToken(String appid) {
		String tokenUrl = WECHAT_TOKEN_SERVER_URL + "/api/wechat/getaccesstoken?appId=" + appid;
		try {
			return WebUtil.getUrlData(tokenUrl);
		} catch (Exception e) {
			return null;
		}
	}

	@Override
	public String getWechatAuthorizeInfo(String access_token, String openid) throws Exception {
		String url = String.format("https://api.weixin.qq.com/sns/userinfo?access_token=%s&openid=%s&lang=zh_CN",
				access_token, openid);
		return WebUtil.getUrlData(url);
	}

	@Override
	public String getWechatInfo(String appid, String openid) throws Exception {
		String url = String.format("https://api.weixin.qq.com/cgi-bin/user/info?access_token=%s&openid=%s&lang=zh_CN",
				getAccessToken(appid), openid);
		return WebUtil.getUrlData(url);
	}

	@Override
	public boolean checkSignature(String signature, String timestamp, String nonce) {
		String[] paramArr = new String[] { WechatCommonConfig.WECHAT_TOKEN, timestamp, nonce };
		Arrays.sort(paramArr);
		String content = paramArr[0].concat(paramArr[1]).concat(paramArr[2]);
		String ciphertext = null;
		try {
			MessageDigest md = MessageDigest.getInstance("SHA-1");
			byte[] digest = md.digest(content.getBytes());
			ciphertext = byteToStr(digest);
		} catch (Exception e) {
			e.printStackTrace();
		}
		return ciphertext != null ? ciphertext.equals(signature.toUpperCase()) : false;
	}

	@Override
	public String processRequest(String appid, Document document) throws Exception {
		try {
			WechatMpMessage wechatMpMessage = MessageUtil.parseXml(document);

			// logger.info(wechatMpMessage.toString());

			User user = null;

			WechatInfo wechatInfo = wechatInfoService.getByOpenid(wechatMpMessage.getFromUserName());
			if (wechatInfo != null) {
				user = userService.get(wechatInfo.getUserId());
			}

			String respStr = ParamType.SUCCESS;

			// 获取到当前发信息到公众号的用户

			if (!StringUtils.isEmpty(wechatMpMessage.getEvent())) {
				switch (wechatMpMessage.getEvent()) {
				case MessageUtil.EVENT_TYPE_SUBSCRIBE:
					// 设置用户关注
					respStr = getWechatMessages(wechatMpMessage.getEvent(), wechatMpMessage);
					if (!StringUtils.isEmpty(respStr)) {
						return respStr;
					}
					break;
				case MessageUtil.EVENT_TYPE_SCAN:
					break;
				case MessageUtil.EVENT_TYPE_UNSUBSCRIBE:
					break;
				case MessageUtil.EVENT_TYPE_CLICK:
					respStr = getWechatMessages(wechatMpMessage.getEventKey(), wechatMpMessage);
					if (!StringUtils.isEmpty(respStr)) {
						return respStr;
					}
					break;
				case MessageUtil.REQ_MESSAGE_TYPE_EVENT:
					break;
				}
			} else {
				switch (wechatMpMessage.getMsgType()) {
				case MessageUtil.REQ_MESSAGE_TYPE_TEXT:

					if (user == null && RegexUtil.isMobile(wechatMpMessage.getContent())) {
						user = userService.get(wechatMpMessage.getContent());
						if (user != null) {
							WechatInfo_ID id = new WechatInfo_ID();
							id.setOpenid(wechatMpMessage.getFromUserName());
							id.setAppid(appid);
							wechatInfo = new WechatInfo();
							wechatInfo.setId(id);
							wechatInfo.setUserId(user.getId());
							wechatInfoService.save(wechatInfo);
							respStr = getWechatMessages(wechatMpMessage.getContent(), wechatMpMessage, "已绑定手机");
						} else {
							respStr = getWechatMessages(wechatMpMessage.getContent(), wechatMpMessage, String.format("未找到手机号码为 %s 的注册用户", wechatMpMessage.getContent()));
						}
					} else if (user != null && RegexUtil.isMobile(wechatMpMessage.getContent())) {
						respStr = getWechatMessages(wechatMpMessage.getContent(), wechatMpMessage, String.format("已绑定手机号码：%s", user.getMobile()));
					} else {
						respStr = getWechatMessages(wechatMpMessage.getContent(), wechatMpMessage, "要回复点什么呢？");
					}

					break;
				}
			}

			return !StringUtils.isEmpty(respStr) ? respStr : ParamType.SUCCESS;
		} catch (Exception e) {
			e.printStackTrace();
			throw e;
		}
	}

	@Override
	public JSONObject getTags() {
		// TODO Auto-generated method stub
		return null;
	}

	@Override
	public String getExpireQrcode(String appid, String sceneStr, long seconds) {
		return WechatUtil.getExpireQrcode(appid, sceneStr, seconds);
	}
	
	public String getWechatMessages(String content, WechatMpMessage wechatMpMessage) {
		return getWechatMessages(content, wechatMpMessage, null);

	}

	public String getWechatMessages(String content, WechatMpMessage wechatMpMessage, String returnContent) {
		TextMessage textMessage = new TextMessage();
		
		if (!StringUtils.isEmpty(returnContent)) {
			textMessage.setContent(returnContent);
		} else {
			textMessage.setContent("openid: " + wechatMpMessage.getFromUserName());
		}
		textMessage.setFromUserName(wechatMpMessage.getToUserName());
		textMessage.setToUserName(wechatMpMessage.getFromUserName());
		textMessage.setCreateTime(new Date().getTime() / 1000);
		textMessage.setMsgType(MessageUtil.RESP_MESSAGE_TYPE_TEXT);
		return MessageUtil.textMessageToXml(textMessage);

	}

	private String getJSSignature(String jsapi_ticket, String nonce_str, String timestamp, String url) {
		String signature = "";
		String str = "jsapi_ticket=" + jsapi_ticket + "&noncestr=" + nonce_str + "&timestamp=" + timestamp + "&url="
				+ url;
		try {
			MessageDigest crypt = MessageDigest.getInstance("SHA-1");
			crypt.reset();
			crypt.update(str.getBytes("UTF-8"));
			signature = byteToHex(crypt.digest());
		} catch (NoSuchAlgorithmException | UnsupportedEncodingException e) {
			e.printStackTrace();
		}
		return signature;
	}

	private String byteToStr(byte[] byteArray) {
		String strDigest = "";
		for (int i = 0; i < byteArray.length; i++) {
			strDigest += byteToHexStr(byteArray[i]);
		}
		return strDigest;
	}

	private String byteToHexStr(byte b) {
		char[] Digit = { '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'A', 'B', 'C', 'D', 'E', 'F' };
		char[] tempArr = new char[2];
		tempArr[0] = Digit[(b >>> 4) & 0X0F];
		tempArr[1] = Digit[b & 0X0F];
		String s = new String(tempArr);
		return s;
	}

	private String byteToHex(final byte[] hash) {
		Formatter formatter = new Formatter();
		for (byte b : hash) {
			formatter.format("%02x", b);
		}
		String result = formatter.toString();
		formatter.close();
		return result;
	}

}
